package com.sy.api;

/**
 * @className: AdminsController
 * @author: Mr.Liu
 * @date: 2025/10/29 14:37
 * @Version: 1.0
 * @description:
 */

import com.sy.PageVO;
import com.sy.ResultVO;
import com.sy.dto.*;
import com.sy.pojo.Admins;
import com.sy.service.AdminsService;
import com.sy.utils.BCryptUtils;
import com.sy.vo.AdminsPageVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/admins")
@Tag(name = "员工管理模块")
public class AdminsController {
    @Resource
    private AdminsService adminsService;
    //创建日志对象
    Logger log= LoggerFactory.getLogger(AdminsController.class);
    @PostMapping("/add")
    @Operation(summary = "新增员工")
    public ResultVO<Object> addAdmin(@RequestBody AdminsAddDTO adminsAddDTO){
        log.info("管理员添加时候的入参:{}",adminsAddDTO);
        Admins admins = new Admins();
        //属性值的赋值-->4个
        BeanUtils.copyProperties(adminsAddDTO,admins);
        admins.setAdminLevel(1);
        admins.setCreateTime(LocalDateTime.now());
        //给密码加密
        String hashPassword = BCryptUtils.hashPassword(admins.getPassword());
        //重新赋值给admins中的密码属性
        admins.setPassword(hashPassword);
        log.info("属性赋值后的管理员信息:{}",admins);
        boolean flag = adminsService.save(admins);
        return flag?ResultVO.success():ResultVO.error("员工添加失败");
    }
    @PostMapping("/page")
    @Operation(summary = "员工列表")
    public ResultVO<PageVO<AdminsPageVO>> page(@RequestBody PageDTO pageDTO){
        PageVO<AdminsPageVO> pageVO = adminsService.adminsPage(pageDTO);
        return ResultVO.success(pageVO);
    }

    @PostMapping("/edit")
    @Operation(summary = "员工编辑")
    public ResultVO<Object> edit(@RequestBody AdminsEditDTO adminsEditDTO) {
        log.info("员工编辑的入参:{}", adminsEditDTO);
        //判断是密码否为空
        if (StringUtils.hasText(adminsEditDTO.getPassword())) {
            //将adminsEditDTO中的密码加密
            String pwd = BCryptUtils.hashPassword(adminsEditDTO.getPassword());
            adminsEditDTO.setPassword(pwd);
        }
        boolean flag = adminsService.updateByPrimaryKeySelective(adminsEditDTO);
        return flag ? ResultVO.success() : ResultVO.error("员工编辑失败");
    }
    @DeleteMapping("/{id}")
    @Operation(summary = "员工删除")
    public ResultVO<Object> deleteAdmins(@PathVariable Integer id){
        return adminsService.removeById(id)?ResultVO.success():ResultVO.error();
    }
}
